#include <ifaddrs.h>

#include <rtc_base/logging.h>
#include "base/network.h"



namespace xrtc {

NetworkManager::~NetworkManager() {
    for (auto network : m_network_list) {
        delete network;
    }

    m_network_list.clear();
}

// 获取网卡中可用ip地址
int NetworkManager::create_networks() {
    struct ifaddrs* interface;
    // 获取所有可用的网络接口信息
    int err = getifaddrs(&interface);
    if (err != 0) {
        RTC_LOG(LS_WARNING) << "getifaddrs error: " << strerror(errno) << ", errno: " << errno;
        return -1;
    }

    
    for (auto cur = interface; cur != nullptr; cur = cur->ifa_next) {
        // 只使用ipv4
        if (cur->ifa_addr->sa_family != AF_INET) {
            continue;
        }

        struct sockaddr_in* addr = (struct sockaddr_in*)cur->ifa_addr;
        rtc::IPAddress ip_addr(addr->sin_addr);

        // 过滤局域网和回环地址
        if (rtc::IPIsPrivateNetwork(ip_addr) || rtc::IPIsLoopback(ip_addr)) {
            continue;
        }
        
        Network* network = new Network(cur->ifa_name, ip_addr);

        RTC_LOG(LS_INFO) << "gathered network interface: " << network->toString();

        m_network_list.push_back(network);
    }

    // 如果列表为空，使用固定公网IP
    if (m_network_list.empty()) {
        RTC_LOG(LS_INFO) << "No public network interface found. Using fixed public IP.";
        // 将字符串"43.139.117.90"转换为rtc::IPAddress
        rtc::IPAddress fixed_public_ip;
        if (rtc::IPFromString("43.139.117.90", &fixed_public_ip)) {
            // 创建一个虚拟的网络接口，名称例如"fallback_public"
            Network* network = new Network("fallback_public", fixed_public_ip);
            m_network_list.push_back(network);
            RTC_LOG(LS_INFO) << "Fallback network interface created: " << network->toString();
        } else {
            RTC_LOG(LS_ERROR) << "Failed to parse the fixed public IP address.";
            return -1; // IP地址格式错误
        }
    }

    freeifaddrs(interface);

    return 0;
}

}
